import 'package:flutter/foundation.dart';
import 'package:photo_manager/photo_manager.dart';
import 'dart:typed_data';

/// 资产缓存服务，用于缓存待上传的资产信息和缩略图
class AssetCacheService {
  // 单例模式
  static final AssetCacheService _instance = AssetCacheService._internal();
  factory AssetCacheService() => _instance;
  AssetCacheService._internal();

  // 缓存的资产列表
  final List<AssetEntity> _cachedAssets = [];

  // 缩略图缓存
  final Map<String, Uint8List?> _thumbnailCache = {};

  // 最大缓存数量
  static const int maxCachedAssets = 20;

  // 缓存状态
  bool _isInitialized = false;
  DateTime? _lastUpdateTime;

  /// 获取缓存的资产列表
  List<AssetEntity> get cachedAssets => List.unmodifiable(_cachedAssets);

  /// 获取缩略图缓存
  Map<String, Uint8List?> get thumbnailCache =>
      Map.unmodifiable(_thumbnailCache);

  /// 缓存是否已初始化
  bool get isInitialized => _isInitialized;

  /// 最后更新时间
  DateTime? get lastUpdateTime => _lastUpdateTime;

  /// 缓存是否需要刷新(10分钟过期)
  bool get needsRefresh {
    if (!_isInitialized || _lastUpdateTime == null) return true;
    final now = DateTime.now();
    return now.difference(_lastUpdateTime!).inMinutes > 10;
  }

  /// 添加资产到缓存
  void addAssets(List<AssetEntity> assets) {
    for (var asset in assets) {
      if (!_cachedAssets.any((a) => a.id == asset.id)) {
        _cachedAssets.add(asset);
      }
    }

    // 限制缓存大小
    if (_cachedAssets.length > maxCachedAssets) {
      final remainingAssets = _cachedAssets.sublist(0, maxCachedAssets);
      _cachedAssets.clear();
      _cachedAssets.addAll(remainingAssets);
    }

    _lastUpdateTime = DateTime.now();
    _isInitialized = true;
  }

  /// 从缓存中移除单个资产
  void removeAsset(String assetId) {
    final int beforeCount = _cachedAssets.length;
    _cachedAssets.removeWhere((asset) => asset.id == assetId);
    final int afterCount = _cachedAssets.length;

    _thumbnailCache.remove(assetId);

    if (beforeCount != afterCount) {
      debugPrint('从资产缓存中移除: $assetId (剩余${_cachedAssets.length}个)');
      _lastUpdateTime = DateTime.now(); // 更新修改时间
    } else {
      debugPrint('资产不在缓存中: $assetId');
    }
  }

  /// 从缓存中移除多个资产
  void removeAssets(List<String> assetIds) {
    for (var id in assetIds) {
      removeAsset(id);
    }
  }

  /// 添加缩略图到缓存
  void addThumbnail(String assetId, Uint8List? thumbnailData) {
    if (thumbnailData == null) return;
    _thumbnailCache[assetId] = thumbnailData;
  }

  /// 批量添加缩略图到缓存
  void addThumbnails(Map<String, Uint8List?> thumbnails) {
    if (thumbnails.isEmpty) return;
    _thumbnailCache.addAll(thumbnails);
  }

  /// 是否包含指定资产的缩略图
  bool hasThumbnail(String assetId) {
    return _thumbnailCache.containsKey(assetId) &&
        _thumbnailCache[assetId] != null;
  }

  /// 获取指定资产的缩略图
  Uint8List? getThumbnail(String assetId) {
    return _thumbnailCache[assetId];
  }

  /// 清空缓存
  void clearCache() {
    _cachedAssets.clear();
    _thumbnailCache.clear();
    _isInitialized = false;
    _lastUpdateTime = null;
  }

  /// 预加载资产缩略图
  Future<void> preloadThumbnails(
    List<AssetEntity> assets, {
    int quality = 80,
  }) async {
    if (assets.isEmpty) return;

    for (var asset in assets) {
      if (!hasThumbnail(asset.id)) {
        try {
          final thumbnailData = await asset.thumbnailDataWithSize(
            const ThumbnailSize(200, 200),
            quality: quality,
          );

          if (thumbnailData != null) {
            addThumbnail(asset.id, thumbnailData);
          }
        } catch (e) {
          debugPrint('预加载缩略图失败: $e');
        }
      }
    }
  }
}
